package drds.plus.executor.cursor.cursor.impl.common;

import drds.plus.executor.cursor.cursor.IReverseOrderByCursor;
import drds.plus.executor.cursor.cursor.ISortingCursor;
import drds.plus.executor.cursor.cursor.impl.SortingCursor;
import drds.plus.executor.row_values.RowValues;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.abstract_syntax_tree.expression.order_by.OrderBy;
import drds.plus.util.GeneralUtil;

import java.util.List;

/**
 * 逆序遍历一个cursor
 */
public class ReverseOrderByCursor extends SortingCursor implements IReverseOrderByCursor {

    public ReverseOrderByCursor(ISortingCursor cursor) throws RuntimeException {
        super(cursor, null, cursor.getOrderByList());
        List<OrderBy> orderByList = cursor.getOrderByList();
        reverseOrderBy(orderByList);
    }

    /**
     * 排序方式各orderBy取反
     *
     * @param orderByList
     */
    private void reverseOrderBy(List<OrderBy> orderByList) {
        if (orderByList != null) {
            for (OrderBy orderBy : orderByList) {
                if (orderBy.getAsc()) {
                    orderBy.setAsc(false);
                } else {
                    orderBy.setAsc(true);
                }
            }
        }
    }

    /**
     * 逆向遍历
     */
    public RowValues next() throws RuntimeException {
        return parentCursorPrev();
    }

    public String toString() {
        return toStringWithInden(0);
    }

    public String toStringWithInden(int inden) {
        StringBuilder sb = new StringBuilder();
        String tab = GeneralUtil.getTab(inden);
        sb.append(tab).append("【Reverse order cursor .").append("\n");
        Utils.printOrderByList(orderByList, inden, sb);
        sb.append(super.toStringWithInden(inden));
        return sb.toString();
    }

}
